<?php
/**
 * 宝贝控制器
 * Class ProductController
 * @package Admin\Controller
 * @author leiying
 */

namespace Admin\Controller;

class GoodsController extends AdminController {

    /**宝贝列表
     * @author leiying
     */
    public function goodsList(){

        $limit = LIMIT;
        $get = I('post.');

        $search_data = array();//筛选数据
        $where = array();//条件

        if(IS_POST){
            session('searchdata_goodslist',$get);
        }else{
            $get_p = I('get.p');
            if($get_p){
                $this->assign('p',I('get.p'));
            }else{
                session('searchdata_goodslist',null);
            }
            $get = $search_data = session('searchdata_goodslist');
        }
        if(isset($get['cat_id']) && $get['cat_id'] != '' && isset($get['cat_name']) && $get['cat_name'] != ''){
            $search_data['cat_id'] = $get['cat_id'];
            $search_data['cat_name'] = $get['cat_name'];
            //树型搜索
            $cat_ids = $this->getCategoryId($get['cat_id']);
            $where['a.cat_id'] = array('in',$cat_ids);
            /*获取搜索的品牌选项*/
            $relation_brand = M('goods_category')->where(array('id'=>$get['cat_id']))->getField("relation_brand");
            if($relation_brand){
                $ids = explode(',',$relation_brand);
                $search_brand = M("brand")->field("brand_id,title")->where(array("brand_id"=>array("in",$ids)))->select();
            }else{
                $search_brand = array();
            }
            $this->assign("search_brand",$search_brand);
        }
        if(isset($get['brand_id']) && $get['brand_id'] != ''){
            $search_data['brand_id'] = $get['brand_id'];
            $where['a.brand_id'] = array('eq',$get['brand_id']);
        }

        if(isset($get['is_up']) && $get['is_up'] != ''){
            $search_data['is_up'] = $get['is_up'];
            $where['a.is_up'] = array('eq',$get['is_up']);
        }
        if(isset($get['is_hot']) && $get['is_hot'] != ''){
            $search_data['is_hot'] = $get['is_hot'];
            $where['a.is_hot'] = array('eq',$get['is_hot']);
        }
        if(isset($get['goods_name']) && $get['goods_name'] != ''){
            $search_data['goods_name'] = $get['goods_name'];
            $where['a.goods_name'] = array('like',"%".$get['goods_name']."%");
        }




        $count = M('goods')->alias('a')->where($where)->count();
        $Page = new  \Think\Page($count, $limit);// 实例化分页类 传入总记录数

        $Page->setConfig('prev', '上一页');
        $Page->setConfig('next', '下一页');
        $Page->setConfig('last', '末页');
        $Page->setConfig('first', '首页');
        $Page->setConfig('theme', '%FIRST%%UP_PAGE%%LINK_PAGE%%DOWN_PAGE%%END%%HEADER%');
        $show = $Page->show();// 分页显示输出
        $this->assign('page',$show);// 赋值分页输出


        $lists = M('goods')
            ->alias('a')
            ->field('a.*,b.name cat_name,c.title brand_title')
            ->join(C('DB_PREFIX')."goods_category b on a.cat_id=b.id",'left')
            ->join(C('DB_PREFIX')."brand c on a.brand_id=c.brand_id",'left')
            ->where($where)
            ->limit($Page->firstRow.','.$Page->listRows)
            ->order('a.add_time desc')
            ->select();

        foreach($lists as $k=>&$v){
            $v['xid'] = $k+1;
        }
        $this->assign('lists',$lists);
        $p = I('get.p',1);
        $this->assign('p',$p);
        $this->assign('searchs',$search_data);

        $this->display();
    }

    /**删除宝贝
     * @author leiying
     */
    public function deleteGoods(){
        $id = I('post.id');
        if(empty($id)){
            $this->error('请选择要操作的数据!');
        }
        $res = M("goods")->where(array('goods_id'=>$id))->delete();
        if($res){
            //删除宝贝属性
            M('goods_attr')->where(array('goods_id'=>$id))->delete();
            $this->success("删除成功");
        }else{
            $this->error("删除失败");
        }
    }

    /**上架、下架，热门推荐
     * @param null $method
     * @author leiying
     */
    public function updateStatus($method=null){
		
		$goods_id = I('post.id');
        if (empty($goods_id)) {
            $this->error('请选择要操作的数据!');
        }
        
        switch ( strtolower($method) ){
            case 'downgoods':
                $res = M("goods")->where(array('goods_id'=>$goods_id))->save(array('is_up'=>2));
                if($res){
                    $this->success("已下架!");
                }else{
                    $this->error("下架失败!");
                }
                break;
            case 'upgoods':
                $res = M("goods")->where(array('goods_id'=>$goods_id))->save(array('is_up'=>1));
                if($res){
                    $this->success("已上架!");
                }else{
                    $this->error("上架失败!");
                }
                break;
            case 'nothot':
                $res = M("goods")->where(array('goods_id'=>$goods_id))->save(array('is_hot'=>0));
                if($res){
                    $this->success("设置不推荐成功!");
                }else{
                    $this->error("操作失败!");
                }
                break;
            case 'ishot':
                $res = M("goods")->where(array('goods_id'=>$goods_id))->save(array('is_hot'=>1));
                if($res){
                    $this->success("设置推荐成功!");
                }else{
                    $this->error("操作失败!");
                }
                break;
            default:
                $this->error($method.'参数非法');
        }
    }

    /**获取分类的子分类id(包含该分类id)
     * @param $cat_id
     * @return array
     * @author leiying
     */
    protected  function getCategoryId($cat_id){
        $tree_list = M('goods_category')->field("id,pid,name")->order("sort asc")->select();
        $res = list_to_tree($tree_list,"id","pid","_child",$cat_id);
        $lists = tree_to_array($res);
        $ids[] = $cat_id;
        foreach($lists as $v){
            $ids[] = $v['id'];
        }
        return $ids;
    }

    /**修改宝贝分类状态
     * @author leiying
     */
    public function updateTypeStatus(){
        if(IS_POST){
            $data["status"] = intval($_POST["status"]);
            $map["id"] = intval($_POST["id"]);
            $result = M('goods_category')->where($map)->save($data);
            if(is_numeric($result)){
                $this->success("执行成功");
            }else{
                $this->error("执行失败");
            }
        }else{
            $this->error('非法操作');
        }
    }



    /**宝贝添加
     * @author leiying
     */
    public function goodsAdd(){
        $post_btn = I("post.btn");
        if($post_btn){$this->success('');}
        if(IS_POST){
            $post = I('post.');
            /*处理参数*/
            /*必填*/
            $goods_name = trim($post['goods_name']);
            if(empty($goods_name)){$this->error("请输入宝贝名称");}
            $highest_price = $post['highest_price'];
            if(empty($highest_price)){
                $this->error("请输入限时最高价");
            }else{
                $this->checkNum($highest_price,'限时最高价');
            }
            $cat_id = $post["cat_id"];
            if(empty($cat_id)){$this->error("请选择宝贝分类");}
            $brand_id = $post["brand_id"];
            if(empty($brand_id)){$this->error("请选择所属品牌");}
            $is_up = $post["is_up"];
            if(!in_array($is_up,array(1,2))){$this->error("请选择是否上架");}
            $is_hot = $post["is_hot"];
            if(!in_array($is_hot,array(0,1))){$this->error("请选择是否为热门推荐");}

            /*选填*/
            $post_sort = trim($post["sort"]);
            $sort = empty($post_sort)?0:intval($post_sort);
            $type_id = $post['type_id'];

            $goods = array(
                'goods_name'=>$goods_name,
                'highest_price'=>$highest_price,
                'cat_id'=>$cat_id,
                'brand_id'=>$brand_id,
                'type_id'=>$type_id,
                'is_up'=>$is_up,
                'is_hot'=>$is_hot,
                'sort'=>$sort,
                'add_time'=>time(),
            );
            $goods_id = M("goods")->add($goods);
            if($goods_id){
                /*关联属性*/
                $attr_id_array = $post["attr_id"];
                $attr_value_array = $post["attr_value"];
                $attr_price_array = $post["attr_price"];
                if(isset($attr_id_array)){
                    $goods_attr = array();
                    foreach($attr_id_array as $key=>$value){
                        $attr_price = trim($attr_price_array[$key])?$attr_price_array[$key]:'0.00';
                        $goods_attr[$key] = array(
                            'goods_id'=>$goods_id,
                            'attr_id'=>$value,
                            'attr_value'=>$attr_value_array[$key],
                            'attr_price'=>$attr_price,
                        );
                    }
                    $res = M("goods_attr")->addAll($goods_attr);
                    if($res){
                        $this->success('提交成功');//有关联属性
                    }else{
                        M("goods")->where(array('goods_id'=>$goods_id))->delete();
                        $this->error("提交失败");
                    }
                }else{
                    $this->success('提交成功');//没有关联属性
                }
            }else{
                $this->error("提交失败");
            }
        }else{
            $tag = I("tag",'parent');
            if($tag){
                $this->assign('tag',$tag);
            }

            /*品牌*/
            $brandList = M("brand")->field("brand_id,title")->where(array("status"=>1))->order("sort asc,updated_at desc")->select();
            $this->assign("brandList",$brandList);
            /*宝贝类型*/
            $typeList = M("goods_type")->field("id,type_name")->where(array("status"=>1))->select();
            $this->assign("typeList",$typeList);

            $this->display();
        }
    }

    /**宝贝编辑
     * @author leiying
     */
    public function goodsEdit(){
        if(I('post.btn')){$this->success('');}
        if(IS_POST){
            $post = I('post.');
            $id = $post['goods_id'];
            if(empty($id)){
                $this->error('请选择要操作的数据!');
            }
            /*处理参数*/
            /*必填*/
            $goods_name = trim($post['goods_name']);
            if(empty($goods_name)){$this->error("请输入宝贝名称");}
            $highest_price = $post['highest_price'];
            if(empty($highest_price)){
                $this->error("请输入限时最高价");
            }else{
                $this->checkNum($highest_price,'限时最高价');
            }
            $cat_id = $post["cat_id"];
            if(empty($cat_id)){$this->error("请选择宝贝分类");}
            $brand_id = $post["brand_id"];
            if(empty($brand_id)){$this->error("请选择所属品牌");}
            $is_up = $post["is_up"];
            if(!in_array($is_up,array(1,2))){$this->error("请选择是否上架");}
            $is_hot = $post["is_hot"];
            if(!in_array($is_hot,array(0,1))){$this->error("请选择是否为热门推荐");}

            /*选填*/
            $post_sort = trim($post["sort"]);
            $sort = empty($post_sort)?0:intval($post_sort);
            $type_id = $post['type_id'];

            $goods = array(
                'goods_name'=>$goods_name,
                'highest_price'=>$highest_price,
                'cat_id'=>$cat_id,
                'brand_id'=>$brand_id,
                'type_id'=>$type_id,
                'is_up'=>$is_up,
                'is_hot'=>$is_hot,
                'sort'=>$sort,
            );
            $res = M("goods")->where(array("goods_id"=>$id))->save($goods);
            if(is_numeric($res)){
                M('goods_attr')->where(array("goods_id"=>$id))->delete();
                /*关联属性*/
                $attr_id_array = $post["attr_id"];
                $attr_value_array = $post["attr_value"];
                $attr_price_array = $post["attr_price"];
                if(isset($attr_id_array)){
                    $goods_attr = array();
                    foreach($attr_id_array as $key=>$value){
                        $attr_price = trim($attr_price_array[$key])?$attr_price_array[$key]:'0.00';
                        $goods_attr[$key] = array(
                            'goods_id'=>$id,
                            'attr_id'=>$value,
                            'attr_value'=>$attr_value_array[$key],
                            'attr_price'=>$attr_price,
                        );
                    }
                    $res = M("goods_attr")->addAll($goods_attr);
                    if($res){
                        $this->success('保存成功');//有关联属性
                    }else{
                        $this->error("属性保存失败");//
                    }
                }else{
                    $this->success('保存成功');//没有关联属性
                }
            }else{
                $this->error("保存失败");
            }
        }else{
            $id = I("get.goods_id");
            if(empty($id)){
                $this->error('请选择要操作的数据!');
            }
            $res = M('goods')
                ->alias('a')
                ->field('a.*,b.name cat_name')
                ->join(C('DB_PREFIX')."goods_category b on a.cat_id=b.id",'left')
                ->where(array('a.goods_id'=>$id))
                ->find();
            $this->assign('res',$res);
            /*宝贝类型*/
            $typeList = M("goods_type")->field("id,type_name")->where(array("status"=>1))->select();
            $this->assign("typeList",$typeList);
            /*品牌*/
            $relation_brand = M('goods_category')->where(array('id'=>$res['cat_id']))->getField("relation_brand");
            if($relation_brand){
                $ids = explode(',',$relation_brand);
                $brandList = M("brand")->field("brand_id,title")->where(array("brand_id"=>array("in",$ids)))->select();
            }else{
                $brandList = array();
            }
            $this->assign("brandList",$brandList);
            /*关联属性*/
            $attrList = M("goods_attr")
                ->alias("a")
                ->field("a.attr_id,b.attr_name,b.attr_input_type,b.attr_select_type")
                ->join(C('DB_PREFIX')."attribute b on a.attr_id=b.attr_id",'left')
                ->where(array('goods_id'=>$id))->group("attr_id")->order("goods_attr_id asc")->select();
            if($attrList){
                foreach($attrList as &$v){
                    $attr = M("goods_attr")
                        ->field("attr_value,attr_price")
                        ->where(array('attr_id'=>$v['attr_id']))->order("goods_attr_id asc")->select();
                    $v["attr"] = $attr;
                }
            }else{
                $attrList = array();
            }
            $this->assign("attrList",$attrList);

            $p = I('get.p',1);
            $this->assign('p',$p);


            $this->display();
        }
    }





    /**整数或小数二位
     * @param $num
     * @param string $desc
     * @param string $type
     * @return bool
     * @author leiying
     */
    public function checkNum($num,$desc='',$type='0'){
        if(preg_match('/^[0-9]+(.[0-9]{1,2})?$/', $num)){
            if($type == '1'){//页面发出的验证请求
                $this->success('符合条件');
            }else{
                return true;
            }
        }else{
            $this->error($desc."请输入整数或小数二位");
        }
    }

    /**整数
     * @param $num
     * @param string $desc
     * @param string $type
     * @return bool
     * @author leiying
     */
    public function checkIntNum($num,$desc='',$type='0'){
        if(preg_match('/^[0-9]+?$/', $num)){
            if($type == '1'){//页面发出的验证请求
                $this->success('符合条件');
            }else{
                return true;
            }
        }else{
            $this->error($desc."请输入整数");
        }
    }

    /**批量操作 热门推荐、上架
     * @author leiying
     *
     */
    public function multiOpera( $method = null ){
        $goods_ids = I('post.goods_id');
        if(!$goods_ids){$this->error("请选择操作数据");}
        switch (strtolower($method) ){
            case 'is_hot':
                $res = M("goods")->where(array("goods_id"=>array("in",$goods_ids)))->save(array("is_hot"=>1));
                if(is_numeric($res)){
                    $this->success("操作成功");
                }else{
                    $this->error("操作失败");
                }
                break;
            case 'not_hot':
                $res = M("goods")->where(array("goods_id"=>array("in",$goods_ids)))->save(array("is_hot"=>0));
                if(is_numeric($res)){
                    $this->success("操作成功");
                }else{
                    $this->error("操作失败");
                }
                break;
            case 'is_up':
                $res = M("goods")->where(array("goods_id"=>array("in",$goods_ids)))->save(array("is_up"=>1));
                if(is_numeric($res)){
                    $this->success("操作成功");
                }else{
                    $this->error("操作失败");
                }
                break;
            case 'not_up':
                $res = M("goods")->where(array("goods_id"=>array("in",$goods_ids)))->save(array("is_up"=>2));
                if(is_numeric($res)){
                    $this->success("操作成功");
                }else{
                    $this->error("操作失败");
                }
                break;
            default:
                $this->error("未知操作");
                break;
        }
    }



}
